package com.timedomain.him.remake.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.annotation.RequiresApi;
import com.timedomain.him.remake.receiver.MorningCallAlarmReceiver;

public class ScheduledEventUtils {


    public static void scheduleAlarmClock(Context ctx,int code, Intent intent,long time){
        long nextTime = time;
        AppSettings.saveSettings(ctx);

        AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
        if(nextTime != -1 && nextTime < TimeUtils.getTimeStampIgnoreTimeZone()){
            ctx.sendBroadcast(intent);
            return;
        }
        boolean isAndroidSorAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S;
        PendingIntent pi = PendingIntent.getBroadcast(ctx,code,intent,(isAndroidSorAbove ? PendingIntent.FLAG_MUTABLE : PendingIntent.FLAG_ONE_SHOT) | PendingIntent.FLAG_UPDATE_CURRENT);
        if(nextTime == -1){
            alarmManager.cancel(pi);
            return;
        }
        AlarmManager.AlarmClockInfo alarmInfo = new AlarmManager.AlarmClockInfo(
                TimeUtils.toSystemTimeStamp(nextTime),
                pi
        );
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if(!alarmManager.canScheduleExactAlarms()){
                    throw new SecurityException("Not allowed to set exact alarm. ");
                }
            }
            alarmManager.setAlarmClock(alarmInfo, pi);
            HLog.d("AlarmManager", "setNextAlarmClock: success");
        }catch (SecurityException ex){
            ex.printStackTrace();
            HLog.e("AlarmManager","不能设置定时任务：未授予对应权限。");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.S)
    public static void openAlarmPermissionScreen(Context ctx){
        Uri uri = Uri.parse("package:"+ctx.getPackageName());
        Intent i = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM,uri);
        ctx.startActivity(i);
    }

}
